package org.example.log;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class SessionLog {
    public SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private ArrayList<String> logs;
    private Map<String,String> times;
    private ArrayList<String> lines;
    public SessionLog(){
        this.logs = new ArrayList<>();
        this.times = new HashMap<>();
        this.lines = new ArrayList<>();
        logs.add("session start at " + dateFormat.format(new Date()));

        File file = new File("session.log");
        if (!file.exists()){
            try{
                if (file.createNewFile()){
                    System.out.println("session.log created!");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        File file2 = new File("time.log");
        if (!file2.exists()){
            try{
                if (file2.createNewFile()){
                    System.out.println("time.log created!");
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    public void add(String command){
        logs.add(dateFormat.format(new Date()) + " " + command);
    }
    public void timesAdd(String filePath,Long openTime){
        Long time = (System.currentTimeMillis() - openTime)/1000;
        times.put(filePath,convertDuration(time));
    }
    public void showCurrent(ArrayList<String> filePaths,ArrayList<Long> openTime){
        for (int i = 0;i < filePaths.size();i++){
            System.out.println(filePaths.get(i) + " " + convertDuration((System.currentTimeMillis() - openTime.get(i))/1000));
        }
    }
    public void showAll(){
        lines.clear();
        readFile();
        for (String line:lines){
            System.out.println(line);
        }
    }
    private void readFile(){
        try(BufferedReader bufferedReader = new BufferedReader(new FileReader("time.log"))){
            String line;
            while ((line = bufferedReader.readLine()) != null){
                lines.add(line);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public void write(){
        logs.add("session ends at" + dateFormat.format(new Date()));

        try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("session.log",true))) {
            for (String line:logs){
                bufferedWriter.write(line);
                bufferedWriter.newLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void writeTime(){
        try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("time.log"))){
            if (lines.size() == 0){
                lookMap(bufferedWriter);
                return;
            }
            for (String line:lines){
                String[] parts = line.trim().split(" ",2);
                String s = convertDuration(convertToSeconds(times.get(parts[0])) + convertToSeconds(parts[1]));
                bufferedWriter.write(parts[0] + " " + s);
                bufferedWriter.newLine();
                times.remove(parts[0]);
            }
            if (times.size() != 0){
                lookMap(bufferedWriter);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
    private void lookMap(BufferedWriter bufferedWriter) throws IOException {
        Set<Map.Entry<String,String>> entrySet = times.entrySet();
        Iterator<Map.Entry<String,String>> iterator = entrySet.iterator();
        while (iterator.hasNext()){
            Map.Entry<String,String> entry = iterator.next();
            bufferedWriter.write(entry.getKey() + " " + entry.getValue());
            bufferedWriter.newLine();
        }
    }
    public String convertDuration(long durationInSeconds) {
        long hours = durationInSeconds / 3600;
        long minutes = (durationInSeconds % 3600) / 60;
        long seconds = durationInSeconds % 60;

        // 构建可读的时长字符串
        StringBuilder result = new StringBuilder();
        if (hours > 0) {
            result.append(hours).append("小时 ");
        }
        if (minutes > 0) {
            result.append(minutes).append("分钟 ");
        }
        if (seconds > 0) {
            result.append(seconds).append("秒");
        }

        return result.toString().trim();
    }
    public long convertToSeconds(String duration) {
        long totalSeconds = 0;
        // 利用正则表达式提取小时和分钟
        String[] parts = duration.split("\\s+");
        for (String part : parts) {
            if (part.contains("小时")) {
                totalSeconds += Integer.parseInt(part.replace("小时", "")) * 3600;
            } else if (part.contains("分钟")) {
                totalSeconds += Integer.parseInt(part.replace("分钟", "")) * 60;
            }else if (part.contains("秒")){
                totalSeconds += Integer.parseInt(part.replace("秒",""));
            }
        }
        return totalSeconds;
    }
}
